<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="780px" :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" class="rule-form">
        <el-form-item label="供应商来源">
          <el-select style="width: 100%;" v-model="ruleForm.faultLevel" filterable placeholder="请选择故障等级"
            @change="handleClickFaultLevel">
            <el-option v-for="(item, i) in ['系统内供应商', '系统外供应商']" :key="i" :label="item" :value="i" />
          </el-select>
        </el-form-item>


        <div v-if="ruleForm.faultLevel == 0">
          <el-form-item label="供应商" prop="supplierIdList" style="width: 100%;">
            <el-select v-model="ruleForm.supplierIdList" value-key="supplierName" multiple placeholder="请选择服务商">
              <el-option v-for="item in supplierList" :key="item.supplierId" :label="item.supplierName"
                :value="item.supplierId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <div v-if="ruleForm.faultLevel == 1">
          <el-form-item label="供应商名称" prop="supplierObj.supplierName">
            <el-input v-model="ruleForm.supplierObj.supplierName" placeholder="请输入供应商名称" />
          </el-form-item>

          <el-form-item label="地址" prop="supplierObj.addr">
            <el-input v-model="ruleForm.supplierObj.addr" placeholder="请输入供应商地址" />
          </el-form-item>

          <el-form-item label="联系人" prop="supplierObj.liaison">
            <el-input v-model="ruleForm.supplierObj.liaison" placeholder="请输入联系人名称" />
          </el-form-item>

          <el-form-item label="联系电话" prop="supplierObj.phone">
            <el-input v-model="ruleForm.supplierObj.phone" placeholder="请输入联系电话" />
          </el-form-item>

          <el-form-item label="官网">
            <el-input v-model="ruleForm.supplierObj.website" placeholder="请输入官网地址" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input type="textarea" placeholder="请输入备注" v-model="ruleForm.supplierObj.remark" maxlength="50"
              show-word-limit>
            </el-input>
          </el-form-item>

          <el-form-item label="图片">
            <upload-image :imgUrl="ruleForm.supplierObj.image" @clearimgUrl="() => ruleForm.image = ''"
              @handleSuccess="handleSuccess">
            </upload-image>
          </el-form-item>

          <el-form-item label="附件">
            <FileUpload v-model="ruleForm.supplierObj.file" :limit="1" :fileSize="50"
              :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
            </FileUpload>
          </el-form-item>
        </div>
      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div class="dialog_footer">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { supplierlist, checkUniqeByName } from '@/api/maintenance/management/Outsourcing.js'
import UploadImage from '@/components/upload/index.vue'
/** ------------------------------------------------------------------------------------------------------------------------------- */

/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  faultLevel: 0,//供应商来源（0系统内供应商，1系统外供应商）==> 不做表单数据
  supplierIdList: [],//系统内的供应商集合

  supplierObj: {
    supplierName: "", //供应商名称
    addr: "", //地址
    liaison: "", //联系人
    phone: "", //联系电话
    website: "", //官网
    image: "", //图片
    file: "", //附件
    remark: "" //备注
  }
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'Form',
  components: {
    UploadImage
  },
  props: {
    parlist: {
      type: Array,
      required: true
    },
  },
  data () {
    return {
      dialogVisible: true,
      ruleForm: Object.assign({}, ruleForm),
      dialogTitle: '添加比选服务商',
      supplierList: [],//供应商数组
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        'supplierObj.supplierName': [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        'supplierObj.addr': [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        'supplierObj.liaison': [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        'supplierObj.phone': [
          {
            required: true,
            pattern: /^((0\d{2,3}-\d{7,8})|(1[35849]\d{9}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur"
          }
        ],
        supplierIdList: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  created () {
    this.handleListType()
    // this.ruleForm.supplierIdList = this.parlist
  },
  methods: {
    // 供应商列表---------------------------------------------
    async handleListType () {
      const { data: res3 } = await supplierlist({ status: 0 })
      this.supplierList = res3
    },

    // 供应商来源选择事件-----------------------------------------------
    handleClickFaultLevel () {
      this.ruleForm.supplierIdList = [];
      for (const key in this.ruleForm.supplierObj) {
        this.ruleForm.supplierObj[key] = '';
      }
    },

    // 图片上传时的处理方法-------------------------------------------
    handleSuccess (res) {
      this.ruleForm.supplierObj.image = res.res.data.url
    },

    // 提交表单-------------------------------------------------------
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.faultLevel == 1) {
            checkUniqeByName({ supplierName: this.ruleForm.supplierObj.supplierName }).then((res) => {
              if (res.data == 0) {
                this.$emit('submit_success', this.ruleForm);
              } else {
                this.$message({
                  message: '已存在相同供应商，请重新输入！',
                  type: 'error'
                })
              }
            })
          } else {
            let Arrs = []
            for (let j = 0; j < this.ruleForm.supplierIdList.length; j++) {
              const b = this.ruleForm.supplierIdList[j];
              for (let index = 0; index < this.supplierList.length; index++) {
                const a = this.supplierList[index];
                if (a.supplierId === b) {
                  Arrs.push(a)
                }
              }
            }
            this.ruleForm.supplierIdList = Arrs
            let arr = [...this.parlist, ...Arrs]
            const newArr = arr.map(item => {
              return item.supplierName
            })
            const isRepeat = newArr.some((x, index, arr) => arr.findIndex(y => y == x) != index);
            if (isRepeat) {
              this.$message({
                message: '请勿重复添加供应商！',
                type: 'warning'
              });
              return
            }
          }

          this.$emit('submit_success', this.ruleForm);

          // const supplierNameFlag = this.supplierList.map(item => item.supplierName).some(item => item == this.ruleForm.supplierObj.supplierName)
          // if (supplierNameFlag) {
          //   this.$message({
          //     message: '请勿填写重复的供应商！',
          //     type: 'error'
          //   })
          //   return false
          // } else {
          // }
        } else {
          this.$message({
            message: '数据验证不通过，检查输入表单',
            type: 'error'
          })
          return false
        }
      })
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      this.ruleForm = Object.assign({}, ruleForm)
      this.ruleForm.supplierIdList = [];
      for (const key in this.ruleForm.supplierObj) {
        this.ruleForm.supplierObj[key] = '';
      }
      this.$emit('click_close')
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
  }
}
</script>
<style lang="scss" scoped>
.form {
  width: 440px;
  margin-left: auto;
  margin-right: auto;

  .inventory {
    display: flex;
  }
}

::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}

.dialog_footer {
  display: flex;
  justify-content: center;
}
</style>
